package com.example.mdc.logback.module.service;

import com.example.mdc.logback.common.config.redis.RedisConfig;
import com.example.mdc.logback.common.resp.ResultResponse;
import com.example.mdc.logback.module.enitity.Balance;
import com.example.mdc.logback.module.mapper.BalanceMapper;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author:      liu_pc
 * Date:        2023/8/25
 * Description: 余额实现类
 * Version:     1.0
 */
@Service
public class BalanceService {

    private final Logger logger = LoggerFactory.getLogger(BalanceService.class);

    private final BalanceMapper balanceMapper;

    private final RedisConfig redisConfig;

    public BalanceService(BalanceMapper balanceMapper, RedisConfig redisConfig) {
        this.balanceMapper = balanceMapper;
        this.redisConfig = redisConfig;
    }

    /**
     * 新增余额信息
     * @param balance 余额信息
     */
    @Transactional(rollbackFor = Exception.class)
    public ResultResponse<?> addBalance(Balance balance) {
        RedissonClient redissonClient = redisConfig.redissonClient();
        //模拟从Token或其他位置获取到唯一资源作为分布式锁的key
        RLock addBalanceLock = redissonClient.getLock("addBalance");
        try {
            logger.info("新增余额信息开始 addBalance,参数-{}", balance);
            //尝试获取锁
            addBalanceLock.lock();
            balanceMapper.insert(balance);
            return ResultResponse.newSuccessInstance();
        } catch (Exception e) {
            logger.error("创建余额信息失败，请稍后重试");
            throw new RuntimeException("创建余额信息失败，请稍后重试", e);
        } finally {
            //释放锁
            addBalanceLock.unlock();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteBalance(String id) {
        // 执行数据库删除操作
        balanceMapper.deleteById(id);
    }


    @Transactional(rollbackFor = Exception.class)
    public void updateBalance(Balance balance) {
        // 执行数据库更新操作
        balanceMapper.updateById(balance);
    }

}
